import { create } from 'zustand';
import type { Cuisine, DataSource } from '@/lib/types';

interface AppState {
  selectedCuisines: Cuisine[];
  selectedSources: DataSource[];
  excludedRestaurants: string[];
  redrawTrigger: number;
  addCuisine: (cuisine: Cuisine) => void;
  removeCuisine: (cuisine: Cuisine) => void;
  toggleCuisine: (cuisine: Cuisine) => void;
  clearCuisines: () => void;
  addSource: (source: DataSource) => void;
  removeSource: (source: DataSource) => void;
  toggleSource: (source: DataSource) => void;
  clearSources: () => void;
  addExcludedRestaurant: (id: string) => void;
  removeExcludedRestaurant: (id: string) => void;
  clearExcludedRestaurants: () => void;
  incrementRedrawTrigger: () => void;
  reset: () => void;
}

export const useAppStore = create<AppState>((set, get) => ({
  selectedCuisines: [],
  selectedSources: [],
  excludedRestaurants: [],
  redrawTrigger: 0,

  addCuisine: (cuisine) =>
    set((state) => ({
      selectedCuisines: state.selectedCuisines.includes(cuisine)
        ? state.selectedCuisines
        : [...state.selectedCuisines, cuisine],
    })),

  removeCuisine: (cuisine) =>
    set((state) => ({
      selectedCuisines: state.selectedCuisines.filter((c) => c !== cuisine),
    })),

  toggleCuisine: (cuisine) => {
    const { selectedCuisines } = get();
    if (selectedCuisines.includes(cuisine)) {
      get().removeCuisine(cuisine);
    } else {
      get().addCuisine(cuisine);
    }
  },

  clearCuisines: () => set({ selectedCuisines: [] }),

  addSource: (source) =>
    set((state) => ({
      selectedSources: state.selectedSources.includes(source)
        ? state.selectedSources
        : [...state.selectedSources, source],
    })),

  removeSource: (source) =>
    set((state) => ({
      selectedSources: state.selectedSources.filter((s) => s !== source),
    })),

  toggleSource: (source) => {
    const { selectedSources } = get();
    if (selectedSources.includes(source)) {
      get().removeSource(source);
    } else {
      get().addSource(source);
    }
  },

  clearSources: () => set({ selectedSources: [] }),

  addExcludedRestaurant: (id) =>
    set((state) => ({
      excludedRestaurants: state.excludedRestaurants.includes(id)
        ? state.excludedRestaurants
        : [...state.excludedRestaurants, id],
    })),

  removeExcludedRestaurant: (id) =>
    set((state) => ({
      excludedRestaurants: state.excludedRestaurants.filter((excludedId) => excludedId !== id),
    })),

  clearExcludedRestaurants: () => set({ excludedRestaurants: [] }),

  incrementRedrawTrigger: () => set((state) => ({ redrawTrigger: state.redrawTrigger + 1 })),
  
  reset: () =>
    set({
      selectedCuisines: [],
      selectedSources: [],
      excludedRestaurants: [],
      redrawTrigger: 0,
    }),
}));
